/*
 * Copyright (c) 2017. jiangyc <710183940@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.jiangyc.bingpictures.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class JsoupUtils {
    // User-Agent: Vivaldi
    private static final String UA_VIVALDI = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.51 Safari/537.36 Vivaldi/1.91.856.16";

    public static Document connect(String url) {
        try {
            return Jsoup.connect(url).userAgent(UA_VIVALDI).get();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Element select(String url, String selector) {
        Document doc = connect(url);

        return doc.select(selector).first();
    }

    public static Elements selectAll(String url, String selector) {
        Document doc = connect(url);

        return doc.select(selector);
    }

    public static String elementText(String url, String selector, String attr) {
        Element element = select(url, selector);

        return element.text();
    }

    public static String elementAttr(String url, String selector, String attr) {
        Element element = select(url, selector);

        return element.attr(attr);
    }

    public static String elementAttr(Document doc, String selector, String attr) {
        Element element = doc.select(selector).first();

        return element.attr(attr);
    }
}
